package com.pdg.dungeondelver.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
import org.newdawn.slick.util.xml.XMLElement;
import org.newdawn.slick.util.xml.XMLElementList;
import org.newdawn.slick.util.xml.XMLParser;


public class ImageManager {

	private Map<String,String> imageResources = new HashMap<String,String>();
	private Map<String,Image> images = new HashMap<String,Image>();
	private Theme theme;
	public Theme getTheme(){
		return theme;
	}
	
	public Image getImage(String key){
		if(imageResources.containsKey(key)){
			if(images.containsKey(key)){
				return images.get(key);
			}else{
				Image image = null;
				try {
					InputStream stream = ResourceLoader.getResourceAsStream(imageResources.get(key));
					image = new Image(stream,imageResources.get(key),false);
				} catch (SlickException e) {
					return null;
				}
				images.put(key, image);
				return image;
			}
		}else{
			return null;
		}
	}
	
	public ImageManager(Theme theTheme,String imagesConfiguration) throws ImageManagerLoadException {
		setTheme(theTheme);
		if(!loadFromXml(imagesConfiguration)){
			throw new ImageManagerLoadException();
		}
	}

	private void setTheme(Theme theTheme) {
		theme = theTheme;
		
	}

	private boolean loadFromXml(String imagesConfiguration) {
		XMLParser parser = new XMLParser();
		try {
			InputStream stream = ResourceLoader.getResourceAsStream(imagesConfiguration);
			XMLElement root = parser.parse(imagesConfiguration,stream);
			XMLElementList children = root.getChildren();
			for(Integer index=0;index<children.size();++index){
				XMLElement child = children.get(index);
				imageResources.put(child.getName(), child.getContent());
			}
			return true;
		} catch (SlickException e) {
			e.printStackTrace();
			return false;
		}
	}

}
